<style>
    .prize {
        padding: 0 30px;
    }

    .formInline .ivu-input-group-prepend .ivu-select-selection,
    .formInline .ivu-input-group-append .ivu-select-selection {
        background-color: #fff !important;
    }

    .award .ivu-select-multiple .ivu-select-selection {
        overflow: hidden !important;
    }
</style>
<style scoped>
</style>

<template>
    <div class="award">
        <product-title></product-title>
        <div class="prize ">
            <div>
                <h3 class="search-h3 huang">分红奖金设置</h3>
            </div>

            <div style="color:red;margin-bottom:15px;">计算公式:
                <span style="color:blue;">个人月度FYC*对应的奖金率（按照人数档次和保单年期档期设定）</span>
            </div>

            <div class="common-box-body">
                <Form :model="formData" ref="formData" :rules="ruleValiFormData">
                    <Row>
                        <Col :md="24" :lg="6">
                        <FormItem label="名称设置 :" prop="name" required>
                            <Input v-model="formData.name" size="large" type="text" placeholder="名称设置" />
                        </FormItem>
                        </Col>
                        <Col :md="24" :lg="6">
                        <FormItem label="适用对象 :" class="search">
                            <Select v-model="formData.rankIds" multiple filterable placeholder="选择适用对象" :transfer=true>
                                <Option v-for="(option, index) in comoptions" :value="option.id" :key="index">{{option.name}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col :md="24" :lg="6">
                        <FormItem label="发放周期 :" prop="configValue.assessmentCycleType" required>
                            <Select v-model="formData.configValue.assessmentCycleType">
                                <Option value="4">月</Option>
                                <Option value="3">季</Option>
                                <Option value="2">半年</Option>
                                <Option value="1">年</Option>
                            </Select>
                        </FormItem>
                        </Col>
                         <Col :md="24" :lg="6">
                        <FormItem label="EM值 :" prop="configValue.em">
                                <Input v-model="formData.configValue.em" placeholder="请输入EM值"></Input>
                        </FormItem>
                        </Col>

                        <Col :md="24" :lg="6">
                        <FormItem prop="enabled" required>
                            <RadioGroup v-model="formData.enabled">
                                是否启用 :
                                <Radio label="1" class="ml15">是</Radio>
                                <Radio label="0">否</Radio>
                            </RadioGroup>
                        </FormItem>
                        </Col>
                        <Col :md="24" :lg="12">
                            &emsp;
                        </Col>
                        <Col style="text-align:right" :md="24" :lg="6">
                        <FormItem>
                            <Button type="success" icon="plus" size="large" @click="addfyc">新增人数档次</Button>
                            <Button type="primary" icon="plus" size="large" @click="addgrade">新增年期档次</Button>
                        </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
            <Row>
                <div class="table-theme highlight_table">
                    <Table :columns="columns" :data="tableList" size="large" stripe highlight-row border></Table>
                    <!-- <Table :columns="columns" :data="data" size="large" stripe highlight-row border></Table> -->
                </div>
            </Row>
            <div id="footer" style="padding:0 30px;">
                <Button type="primary" shape="circle" id="submit" @click="data1" :disabled="tableaction" style="border-radius: 30px !important;margin-top:25px;">
                    <Icon type="checkmark-circled"></Icon>
                    保存 / 提交
                </Button>
                <Button id="back" shape="circle" @click="$router.back(-1)" style="border-radius: 30px !important;background:#77B4F5;color:white;font-size:14px;margin-top:25px;">返回</Button>
            </div>
        </div>
        <Modal v-model="fyc" title="设置人数" :mask-closable="false" :closable="false" class-name="common-box-body formInline">
            <Form class="" :model="money" ref="money" :rules="ruleValifyc">
                <Row>
                    <Col span="6">
                    <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">人数档次 :</div>
                    </Col>
                    <Col span="18">
                    <FormItem prop="groupUpLowLimitValue">
                        <Input placeholder="请输入人数" v-model="money.groupUpLowLimitValue">
                        <Select slot="prepend" style="width: 120px" v-model="max">
                            <Option value="<">最大值</Option>
                        </Select>
                        </Input>
                    </FormItem>
                    <FormItem prop="groupUpOverLimitValue">
                        <Input placeholder="请输入人数" v-model="money.groupUpOverLimitValue">
                        <Select slot="prepend" style="width: 120px" v-model="min">
                            <Option value="≤">最小值</Option>
                        </Select>
                        </Input>
                    </FormItem>
                    </Col>
                </Row>

                <Row v-for="(item, index) in fycData">
                    <Col>
                    <Col span="6">
                    <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">{{item.time}} :</div>
                    </Col>
                    <Col span="18">
                    <FormItem>
                        <Input placeholder="请输入对应年期的奖金率" v-model="item.prize"></Input>
                    </FormItem>
                    </Col>
                    </Col>
                </Row>
            </Form>
            <div slot="footer" :md="24" :lg="8">
                <Button style="width:60px;" type="primary" size="small" @click="cancelfycModal">取消</Button>
                <Button style="width:60px;" class="tRight" type="success" size="small" long @click="addfycModal">确定添加</Button>
            </div>
        </Modal>
        <Modal v-model="grade" title="设置年期档次" :mask-closable="false" :closable="false" class-name="common-box-body formInline">
            <Form class="" :model="timing" ref="timing" :rules="ruleValiTim">
                <Row>
                    <Col span="6">
                    <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">年期档次 :</div>
                    </Col>
                    <Col span="18">
                    <FormItem prop="timeLowLimitValue" required>
                        <Input placeholder="请输入" v-model="timing.timeLowLimitValue">
                        <Select slot="prepend" style="width: 120px" v-model="max">
                            <Option value="<">最大值</Option>
                        </Select>
                        </Input>
                    </FormItem>
                    <FormItem prop="timeHighLimitValue" required>
                        <Input placeholder="请输入" v-model="timing.timeHighLimitValue">
                        <Select slot="prepend" style="width: 120px" v-model="min">
                            <Option value="≤">最小值</Option>
                        </Select>
                        </Input>
                    </FormItem>
                    </Col>
                </Row>

                <Row v-for="(item, index) in gradeData">
                    <Col>
                    <Col span="6">
                    <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">{{item.title}}</div>
                    </Col>
                    <Col span="18">
                    <FormItem>
                        <Input placeholder="请输入对应人数的奖金率" v-model="item.prize"></Input>
                    </FormItem>
                    </Col>
                    </Col>
                </Row>
            </Form>
            <div slot="footer" :md="24" :lg="8">
                <Button style="width:60px;" type="primary" size="small" @click="cancelGradeModal">取消</Button>
                <Button style="width:60px;" class="tRight" type="success" size="small" long @click="addGradeModal">确定添加</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import productTitle from '../../components/productTitle'
    import {
        get_all_rule,
        get_add_rule,
        get_rule_list,
        del_rule,
        get_rank
    } from '../../api/rule'
    import {
        parteGetByName
    } from '../../api/parter'
    import util from '../../libs/util.js';
    export default {
        data() {
            return {
                tabgroup: {},
                data:[],
                max:"<",
                min:"≤",
                gradeData: [],
                fycData: [],
                getNowRate: {},
                prizeShow: false,
                comoptions: [],
                formData: {
                    tempalteId: this.$route.params.tempalteId,
                    name: '',
                    rankIds: [],
                    enabled: '',
                    assessmentCycleType:'',
                    configValue:{
                        assessmentCycleType: '',
                        list:[],
                        ruleName:'分红奖',
                        em:'',
                    },
                },
                money: {
                    'groupUpOverLimitValue': '',
                    'groupUpLowLimitValue': '',
                },
                timing: {
                    timeHighLimitValue: "",
                    timeLowLimitValue: "",
                    prize: '',
                },
                disabled: true,
                fyc: false,
                grade: false,
                tableList: [],
                column1: {
                    type: 'index',
                    title: '序号',
                    align: 'center',
                    width: '80'
                },
                column2: {
                    title: '年期人数档次',
                    key: 'a0',
                    align: 'center'
                },
                columns: [{
                        type: 'index',
                        title: '序号',
                        align: 'center',
                        width: '80'
                    },
                    {
                        title: '团队年期人数档次',
                        key: 'a0',
                        align: 'center',
                    },

                ],
                caozuoKey: false,
                caozuo: {
                    width: '80',
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'large'
                                },
                                style: {
                                    padding: '3px'
                                },
                                on: {
                                    click: () => {
                                        this.remove(params.index)
                                    }
                                }
                            }, '删除')
                        ])
                    }
                },
                tableaction: false,
                ruleValiFormData: {
                    name: [{
                        required: true,
                        message: '名称不能为空',
                        trigger: 'blur,change'
                    }],
                    // rankIds: [{
                    //     required: true,
                    //     message: '请选择一个适用对象',
                    //     trigger: 'blur,change'
                    // }],
                    'configValue.em': [{
                        required: true,
                        message: '请输入正确数字',
                        trigger: 'change',
                        pattern:/^[0-9]+$/,
                    }],
                    'configValue.assessmentCycleType': [{
                        required: true,
                        message: '请选择发放周期',
                        trigger: 'blur,change'
                    }],
                    enabled: [{
                        required: true,
                        message: '请选择是否启用',
                        trigger: 'blur,change'
                    }],
                },
                ruleValifyc: {
                    groupUpLowLimitValue: [{
                        required: true,
                        message: '最大值不能为空',
                        trigger: 'blur'
                    },{ required: true, pattern: /^[z0-9*]*$/, message: '只能输入数字', trigger: 'blur' }],
                    groupUpOverLimitValue: [{
                        required: true,
                        message: '最小值不能为空',
                        trigger: 'blur'
                    },{ required: true, pattern: /^[z0-9*]*$/, message: '只能输入数字', trigger: 'blur' }],
                },
                ruleValiTim: {
                    timeLowLimitValue: [{
                        required: true,
                        message: '最大值不能为空',
                        trigger: 'blur'
                    },{ required: true, pattern: /^[z0-9*]*$/, message: '只能输入数字', trigger: 'blur' }],
                    timeHighLimitValue: [{
                        required: true,
                        message: '最小值不能为空',
                        trigger: 'blur'
                    },{ required: true, pattern: /^[z0-9*]*$/, message: '只能输入数字', trigger: 'blur' }],
                },
            }
        },
        components: {
            productTitle
        },
        created() {
            this.cominit();
            if (this.$route.params.id) {
                var _this = this;
                var url =
                    BASE_URL1+"/kb/v1/rule/salary/config/" +
                    this.$route.params.id;
                util.ajax
                    .get(url, {})
                    .then(function(res) {
                    if (res.data.err == 0) {
                        if (res.data.data.configValue.length > 10) {
                        _this.formData.id = res.data.data.id;
                        _this.formData.name = res.data.data.name;
                        _this.formData.rankIds = res.data.data.rankSet;
                        _this.formData.enabled = res.data.data.enabled ? "1" : "0";
                        _this.formData.assessmentCycleType = res.data.data.assessmentCycleType ? res.data.data.assessmentCycleType : "";
                        _this.formData.configValue.assessmentCycleType = JSON.parse(
                            res.data.data.configValue
                        ).assessmentCycleType;
                        _this.formData.configValue.list = JSON.parse(
                            res.data.data.configValue
                        ).list;
                         _this.formData.configValue.em = JSON.parse(
                            res.data.data.configValue
                        ).em;
                         _this.formData.configValue.ruleName = JSON.parse(
                            res.data.data.configValue
                        ).ruleName;
                        // _this.tableList = _this.formData.configValue.list;
                        _this.tabgroup = _this.formData.configValue;
                        _this.getList();
                        }
                    }
                    })
                    .catch(error => {
                    console.log(666);
                    });
                }
        },
        methods: {
            cominit() {
                new Promise((resolve, reject) => {
                    // get_rank().then(response => {
                        get_rank().then(response => {
                        if (response.data.err == 0) {
                            this.comoptions = response.data.data;
                        } else {
                            this.$Message.error(response.data.info);
                        }
                        resolve();
                    }).catch(error => {
                        reject(error);
                    });
                });
            },
            addfyc() {
                this.fyc = true;
                this.fycData = [];
                for (var i in this.tableList) {
                    let fycObj = {};
                    fycObj.time = this.tableList[i].a0;
                    fycObj.prize = ''
                    this.fycData.push(fycObj)
                }
            },
            addgrade() {
                this.gradeData = this.columns.slice(2, (this.columns.length - 1));
                console.log(this.gradeData)
                if (this.gradeData.length == 0) {
                    this.$Message.error("请先添加人数档次")
                } else {
                    this.grade = true;
                    let _this= this;
                    this.gradeData.map((item,index)=>{
                        _this.gradeData[index].prize =""; 
                    })
                }
            },
            addfycModal() {
                this.$refs['money'].validate((valid) => {
                    if (valid) {
                        let _this = this;
                        if (_this.columns[_this.columns.length - 1].title == '操作') {
                            _this.columns = _this.columns.slice(0, (_this.columns.length - 1));
                        }
                        _this.money = JSON.parse(JSON.stringify(_this.money))
                        if (parseInt(_this.money.groupUpLowLimitValue) <= parseInt(_this.money.groupUpOverLimitValue)) {
                            _this.money.groupUpLowLimitValue = "";
                            _this.money.groupUpOverLimitValue = "";
                            _this.$Message.error("最小值设置不能大于输入的最大值");
                            return false;
                        }
                        _this.columns.push({
                            key: 'a',
                            title: _this.money.groupUpOverLimitValue + '≤人数<' + _this.money.groupUpLowLimitValue,
                            align: 'center'
                        })
                        _this.columns.push(_this.caozuo);
                        let columnsData = _this.columns.slice(2, (_this.columns.length - 1))
                        let len = columnsData.length;
                        for (var i = 2; i < (len + 2); i++) {
                            _this.columns[i].key = 'a' + (i - 1)
                        }
                        if (_this.fycData) {
                            var int = 'a' + len;
                            for (var t in _this.fycData) {
                                _this.tableList[t][int] = _this.fycData[t].prize;
                            }
                        }
                        // 关闭弹框 进行置空 下次进来再重新取数据
                        _this.fyc = false;
                        _this.fycData = [];
                        
                        _this.money.groupUpLowLimitValue = '';
                        _this.money.groupUpOverLimitValue = '';
                        _this.$refs['money'].resetFields();
                    }
                });
            },
            cancelfycModal() {
                this.fyc = false;
                // 关闭弹框 进行置空 下次进来再重新取数据
                this.fycData = [];
                this.$refs['money'].resetFields();
            },
            addGradeModal() {
                this.$refs['timing'].validate((valid) => {
                    if (valid) {
                        if (parseInt(this.timing.timeLowLimitValue) <= parseInt(this.timing.timeHighLimitValue)) {
                            this.timing.timeHighLimitValue = "";
                            this.timing.timeLowLimitValue = "";
                            this.$Message.error("最小值设置不能大于输入的最大值");
                            return false;
                        }
                        var _this = this;
                        var gradeObj = {};
                        gradeObj.a0 = _this.timing.timeHighLimitValue + '≤年期<' + _this.timing.timeLowLimitValue;
                        for (var j = 1; j <= _this.gradeData.length; j++) {
                            var ind = 'a' + j;
                            gradeObj[ind] = _this.gradeData[j - 1].prize;
                        }
                        _this.tableList.push(gradeObj);
                        this.grade = false;
                        _this.timing.timeLowLimitValue = '';
                        _this.timing.timeHighLimitValue = '';
                        this.$refs['timing'].resetFields();
                    }
                })
            },
            cancelGradeModal() {
                this.grade = false;
                this.$refs['timing'].resetFields();
            },
            // 点击删除
            remove(index) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '是否要删除该条记录?',
                    onOk: () => {
                        this.tableList.splice(index, 1)
                    },
                });
            },
            data1() {
                this.tableaction = true;
                setTimeout(() => {
                    this.tableaction = false;
                }, 2000);
                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        let _this = this;
                        let array1 = [];
                        _this.formData.rankIds = _this.formData.rankIds.join();
                        _this.formData.configValue.list=[];
                        let len = _this.columns.length - 1;
                        for (let a = 2; a < len; a++) {
                            let arr1 = _this.columns[a].title.split('≤人数<');
                            array1.push({
                                groupUpLowLimitValue: arr1[1],
                                groupUpOverLimitValue: arr1[0],
                                prize: '',
                            });
                        }
                        for (let i = 0; i < _this.tableList.length; i++) {
                            let _object = {};
                            let arr = _this.tableList[i].a0.split('≤年期<');
                            _object['timeHighLimitValue'] = arr[1];
                            _object['timeLowLimitValue'] = arr[0];
                            _object['list'] = [];
                            _object['list'] = array1;
                            for (let b = 0; b < _object['list'].length; b++) {
                                _object['list'][b].prize = _this.tableList[i]['a' + (b * 1 + 1)].toString();
                            }
                            _this.formData.configValue.list.push(JSON.parse(JSON.stringify(_object)));
                        }
                        let form  = Object.assign({},_this.formData);
                        form.configValue = JSON.stringify(form.configValue);
                        form.assessmentCycleType = form.configValue.assessmentCycleType;
                        if(_this.$route.params.id){
                            let url =
                                BASE_URL1+"/kb/v1/rule/salary/config/" + form.id;
                                util.ajax.post(url, form).then(res => {
                                if (res.data.err == 0) {
                                    _this.$Message.success("操作成功");
                                    _this.$router.push({ name: "rulelist" });
                                } else {
                                    _this.$Message.error("操作失败");
                                }
                                });
                        }else{
                            new Promise((resolve, reject) => {
                            get_add_rule(form).then(response => {
                                if (response.data.err == 0) {
                                        // _this.$refs['formData'].resetFields();
                                        this.$router.push({
                                            name:'rulelist'
                                        });
                                } else {
                                    _this.$refs['formData'].resetFields();
                                    _this.$Message.error(response.data.info);
                                }
                                
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                        }
                        
                    } else {
                        _this.$Message.error("数据填写有误!未通过验证")
                    }
                })
            },
            getList() {
                    let params = {};
                    new Promise((rev, rej) => {
                    })
                        let _this = this;
                         let len = this.tabgroup.list[0].list.length
                        for(var i=0;i<len;i++){
                            this.columns.push({
                                    key:'a'+(i+1),
                                    title:_this.tabgroup.list[0].list[i].groupUpOverLimitValue+'≤人数<'+_this.tabgroup.list[0].list[i].groupUpLowLimitValue,
                                    align:'center'
                                })
                        }
                        for(var a=0;a<this.tabgroup.list.length;a++){
                             _this.tableList[a]={};
                             _this.tableList[a]['a0']=_this.tabgroup.list[a].timeLowLimitValue+'≤年期<'+_this.tabgroup.list[a].timeHighLimitValue;
                            for(var b=0;b<_this.tabgroup.list[a].list.length;b++){
                                var index = 'a'+(b+1);
                                let obj={};
                                // obj[index] = _this.tabgroup.list[a].list[b].prize;
                                _this.tableList[a][index] = _this.tabgroup.list[a].list[b].prize
                            }
                        }
                         this.columns.push(this.caozuo);
                },
        }

    }
</script>